package org.bdware.doip.endpoint.doipServer;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.stream.ChunkedWriteHandler;
import org.apache.log4j.Logger;
import org.bdware.doip.core.codec.packet.PacketNettyWSCodec;
import org.bdware.doip.core.utils.GlobalConfigurations;

public class NettyWSDoipListener extends NettyDoipListener {

    private final int port;
    private final String path;
    static Logger logger = Logger.getLogger(NettyTCPDoipListener.class);
    private Channel ch;

    protected NettyWSDoipListener(int port,String path){
        this.port = port;
        this.path = path;
    }

    @Override
    public void start() {
        if(handler == null){
            logger.error("Handler not init yet! set handler first");
            return;
        }
        EventLoopGroup bossGroup = new NioEventLoopGroup(1);
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap b = new ServerBootstrap();
            b.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .localAddress(port);
            b.childHandler(
                    new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ch.pipeline()
                                    //基于HTTP
                                    .addLast(new HttpServerCodec())
                                    // 对写大数据流的支持
                                    .addLast(new ChunkedWriteHandler())
                                    .addLast(new HttpObjectAggregator(GlobalConfigurations.defaultMsgMTU))
                                    .addLast(new WebSocketServerProtocolHandler(path))
                                    .addLast(new PacketNettyWSCodec())
                                    .addLast(handler);
                        }
                    });

            ch = b.bind().syncUninterruptibly().channel();
            logger.info("WS DOIP listener start at:" + port + path);
            ch.closeFuture().sync();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            bossGroup.shutdownGracefully();
        }
    }

    @Override
    public void stop() {
        ch.close();
    }
}
